package com.nut.web;

import com.alibaba.fastjson.JSON;
import com.nut.common.Result;
import com.nut.pojo.Book;
import com.nut.pojo.FileObj;
import com.nut.pojo.OrderVo;
import com.nut.pojo.Page;
import com.nut.service.BookService;
import com.nut.service.impl.BookServiceImpl;
import com.nut.utils.JsonUtils;
import com.nut.utils.QiNiuUtils;
import com.nut.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.nut.web.clientOrderServlet.getPostData;

public class BookServlet extends BaseServlet{

    private BookService bookService = new BookServiceImpl();
    protected void pageByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取请求的参数pageNo,pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        String name = req.getParameter("name");
        //2、调用BookService.page()方法
        Page<Book> page = bookService.pageByName(pageNo,pageSize,name);
        resp.getWriter().write(JsonUtils.toJson(Result.ok().data("page",page)));
    }
    /**
     * 添加
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookData = getPostData(req);
        Gson gson = new Gson();
        Book book = gson.fromJson(bookData, Book.class);
        //添加图书
        bookService.addBook(book);
        if (book.getName() != null){
            resp.getWriter().write(JsonUtils.toJson(Result.ok().message("添加成功")));
        }
        else {
            resp.getWriter().write(JsonUtils.toJson(Result.error().message("书获取失败")));
        }
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取请求的参数id，图书编程
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //2、调用bookService.deleteBookById();删除图书
        bookService.deleteBookById(id);
        resp.getWriter().write(JsonUtils.toJson(Result.ok().message("成功")));
    }
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookData = getPostData(req);
        Gson gson = new Gson();
        Book book = gson.fromJson(bookData, Book.class);
        // 1、获取请求的参数==封装成为Book对象
        // 2、调用BookService.updateBook( book );修改图书
        bookService.updateBook(book);
        resp.getWriter().write(JsonUtils.toJson(Result.ok().message("修改图书成功")));

    }
    protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数图书编号
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //2 调用bookService.queryBookById查询图书
        Book book = bookService.queryBookById(id);
        //3 保存到图书到Request域中
        //req.setAttribute("book",book);
        resp.getWriter().write(JsonUtils.toJson(Result.ok().data("book",book)));

    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 通过BookService查询全部图书
        List<Book> books = bookService.queryBooks();
        //2 把全部图书保存到Request域中
        //req.setAttribute("books", books);
        resp.getWriter().write(JsonUtils.toJson(Result.ok().data("books",books)));
    }
    private static Map<String,String> getFilePath(HttpServletRequest request) {
        String slashDirectory = "/";
        // 上传配置
        int memoryThreshold   = 1024 * 1024 * 3;  // 3MB
        int maxFileSize      = 1024 * 1024 * 40; // 40MB
        int maxRequestSize   = 1024 * 1024 * 50; // 50MB
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(memoryThreshold);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值
        upload.setFileSizeMax(maxFileSize);
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(maxRequestSize);
        upload.setHeaderEncoding("UTF-8");
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d= new Date();
        String newFileName = sdf.format(d).split(" ")[0];
        String uploadPath =  "D:\\pic\\"+newFileName;
        String fileName="";
        String filePath="";
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        Map paramMap = new HashMap();

        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        fileName = new File(item.getName()).getName();
                        filePath = uploadPath + slashDirectory + fileName;
                        System.out.println("filePath:"+filePath);
                        File storeFile = new File(filePath);
                        item.write(storeFile);
                        QiNiuUtils.upload2Qiniu(storeFile,fileName);
                        paramMap.put("fileName", fileName);
                        paramMap.put("filePath", filePath);
                    }else {
                        String value = item.getString("utf-8");
                        paramMap.put(item.getFieldName(), value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paramMap;
    }
    protected void updateBookPicture(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> map = getFilePath(req);
        bookService.updatePicture(map, Integer.parseInt(req.getParameter("id")));
        resp.getWriter().write(JsonUtils.toJson(Result.ok()));
    }
    protected void downloadPicture(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        bookService.downloadPicture(id);
        resp.getWriter().write(JsonUtils.toJson(Result.ok()));
    }
}
